﻿using CKS.Core.Framework;
using CKS.PLC.Core.Cache;
using FreeSql;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Enum;
using ZR.Model.Models.ProductionControl;
using static FreeSql.Internal.GlobalFilter;


namespace CKS.PLC.Action
{
    public  abstract partial class PLCAction
    {
        public long GetNextSeq(CksVirtualTable table)
        {
            var n = conn.Select<CksVirtualTable>().Where(a => a.TableName == table.TableName).First();
            return n.MaxSeqId + 1;
        }

        /// <summary>
        /// 查询符合条件的第一条记录，以字典返回
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="wheresql"> Id=@Id AND ... </param>
        /// <param name="parms">eg:new { xx=""}</param>
        /// <returns></returns>
        public Dictionary<string,object> GetDynamicTableFirstData(string tableName,string wheresql,object parms = null)
        {
            var vt = conn.Select<CksVirtualTable>().Where(a => a.TableName == tableName).First();
            var columnQuery = conn.Select<CksVirtualColumn>().Where(a => a.TableId == vt.Id).OrderBy(a => a.Sequence);
            var columns = columnQuery.ToList();
            var table = ServiceCommon.GetFreesqlTableInfo(vt, columns);
            
            var model = conn.Select<object>().AsType(table.Type)
                 .Where(wheresql, parms)
                 .OrderBy(" Id desc ")
                 .First().Adapt<Dictionary<string, object>>();
            return model;
        }

    }
}
